import { createRouter, createWebHashHistory } from "vue-router";

export const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/components/Tabbar/index.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Home/index.vue')
      },
      {
        path: 'addressBook',
        name: 'AddressBook',
        component: () => import('@/views/AddressBook/index.vue'),
        meta: {
          keepAlive: true
        }
      },
      {
        path: 'me',
        name: 'Me',
        component: () => import('@/views/Me/index.vue')
      },
    ]
  },
  {
    path: '/chatRoom',
    name: 'ChatRoom',
    component: () => import('@/views/ChatRoom/index.vue'),
  },
  {
    path: '/addFriend',
    name: 'AddFriend',
    component: () => import('@/views/AddFriend/index.vue'),
  },
  {
    path: '/idCard',
    name: 'IdCard',
    component: () => import('@/views/IdCard/index.vue'),
    meta: {
      keepAlive: true
    }
  },
  {
    path: '/myIdCard',
    name: 'MyIdCard',
    component: () => import('@/views/MyIdCard/index.vue'),
  },
  {
    path: '/setting',
    name: 'Setting',
    component: () => import('@/views/Setting/index.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register/index.vue'),
  },
  {
    path: '/newFriendsList',
    name: 'NewFriendsList',
    component: () => import('@/views/NewFriendsList/index.vue'),
  },
]

const router = createRouter({
  scrollBehavior: () => ({ left: 0, top: 0 }),
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  let whiteList = ['/login', '/register']
  let isLogin = Number(localStorage.getItem('isLogin')) || 0
  if (isLogin) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router